//
//  PanelInstallAlertView.swift
//  ezyform
//
//  Created by MoennigQ on 13/1/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SnapKit
import MBProgressHUD
import SDWebImage
import RxCocoa
import RxSwift
class PanelInstallAlertView: GreenNaviBarView {
    lazy var disposeBag = DisposeBag()
    //date picker
    let pickerBackView = UIView()
    let datePicker = UIPickerView()
    
    
    var currentYear: Int = 0
    var currentMonth: Int = 0
    var currentDay: Int = 0
    
    var yearsForPicker: [String] = []
    var monthsForLastYear:[String] = []
    var monthsNumberForLastYear:[String] = []
    var monthsForThisYear:[String] = []
    var monthsNumberForThisYear:[String] = []
    
    var selectYear: String = ""
    var selectMonth: String = ""
    var selectDay: String = ""
    //
    let scrollView = DIYScrollView()
    let installedPanelsCnt = ContentLabel(hexStr: "#379657FF")
    let installationAddressLabel = ContentLabel(hexStr: "#379657FF")
    let dataOfCompletionTextfield = TextFieldWithRequiredView()
    let calenderBtn = UIButton()
    let tableView = UITableView()
    //底部操作按钮
    let cancelBtn = OperationButton(R.string.localizable.cancel(), backColor: UIColor(hexStr: "#70798A"))
    let continueBtn = OperationButton(R.string.localizable.continue())
    
    //
    var tableViewHeightConstraint: Constraint?

    //ESC图片显示及切换view
    var dataObserver: BehaviorRelay<[BrowseImageData]> = BehaviorRelay(value: [])
    //预览图片
    var escImageViewTapBtnClosure: ((_ rowIndex: Int)->Void)?
    //
    
    override func setUpView() {
        //初始化picker的数据
        self.initData()
        //
        self.backgroundColor = .white
        let btnWidth = (APPConfig.WidthForPortrait - 16 * 2 - 20) / 2
        //cancel btn
        self.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.bottom.equalTo(OperationButton.bottomMargin)
            make.left.equalTo(16)
            make.height.equalTo(OperationButton.height)
            make.width.equalTo(btnWidth)
        }
        //continue btn
        self.addSubview(continueBtn)
        continueBtn.snp.makeConstraints { make in
            make.left.equalTo(self.cancelBtn.snp.right).offset(20)
            make.right.equalTo(-16)
            make.height.width.bottom.equalTo(self.cancelBtn)
        }
        scrollView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        scrollView.backgroundColor = .white
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topBackView.snp.bottom).offset(-20)
            make.left.right.equalTo(self)
            make.bottom.equalTo(self.cancelBtn.snp.top)
        }
        
        let contentView = UIView()
        contentView.backgroundColor = .clear
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(scrollView)
            make.left.right.equalTo(self)
            make.height.greaterThanOrEqualTo(0)
        }
        //
        let descripLabel = ContentLabel(hexStr: "#292D3299" )
        descripLabel.text = NSLocalizedString("pvd.detail.editaddress.tip", comment: "")
        descripLabel.textAlignment = .left
        descripLabel.numberOfLines = 0
        contentView.addSubview(descripLabel)
        descripLabel.snp.makeConstraints { (make) in
            make.top.equalTo(20)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(0)
        }
        //installed panel number title
        let installedPanelTitle = ContentLabel()
        installedPanelTitle.text = NSLocalizedString("pvd.detail.editaddress.installedPanelNumbers.count.title", comment: "")
        installedPanelTitle.numberOfLines = 0
        contentView.addSubview(installedPanelTitle)
        installedPanelTitle.snp.makeConstraints { (make) in
            make.top.equalTo(descripLabel.snp.bottom).offset(20)
            make.left.right.equalTo(descripLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        //installed panel number
        contentView.addSubview(installedPanelsCnt)
        installedPanelsCnt.snp.makeConstraints { (make) in
            make.top.equalTo(installedPanelTitle.snp.bottom).offset(12)
            make.left.right.equalTo(descripLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        
        //installation address title
        let installationAddressTitle = ContentLabel()
        installationAddressTitle.text = R.string.localizable.installationAddress() + ":"
        installationAddressTitle.numberOfLines = 0
        contentView.addSubview(installationAddressTitle)
        installationAddressTitle.snp.makeConstraints { (make) in
            make.top.equalTo(installedPanelsCnt.snp.bottom).offset(20)
            make.left.right.equalTo(descripLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        //date of completion
        installationAddressLabel.numberOfLines = 0
        installationAddressLabel.adjustsFontSizeToFitWidth = true
        contentView.addSubview(installationAddressLabel)
        installationAddressLabel.snp.makeConstraints { (make) in
            make.top.equalTo(installationAddressTitle.snp.bottom).offset(12)
            make.left.right.equalTo(descripLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        //date of completion title
        let dateOfCompletionTitle = LabelWithRedStarView(R.string.localizable.pleaseSelectDateOfTest())
        contentView.addSubview(dateOfCompletionTitle)
        dateOfCompletionTitle.snp.makeConstraints { (make) in
            make.top.equalTo(installationAddressLabel.snp.bottom).offset(20)
            make.left.right.equalTo(descripLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        //date of completion
        dataOfCompletionTextfield.textField.textColor = UIColor(hexStr: "#379657")
        dataOfCompletionTextfield.textField.isEnabled = false
        dataOfCompletionTextfield.textField.rightViewMode = .always
        dataOfCompletionTextfield.textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 0))
        contentView.addSubview(dataOfCompletionTextfield)
        dataOfCompletionTextfield.snp.makeConstraints { (make) in
            make.top.equalTo(dateOfCompletionTitle.snp.bottom).offset(12)
            make.left.right.equalTo(descripLabel)
            make.height.greaterThanOrEqualTo(0)
            
        }
        
        //calender btn
        calenderBtn.setImage(UIImage(named: "installation_detail_checklist_panelinstall_alert_calender"), for: UIControl.State.normal)
        calenderBtn.contentMode = .center
        dataOfCompletionTextfield.addSubview(calenderBtn)
        calenderBtn.snp.makeConstraints { (make) in
            make.right.equalTo(-8)
            make.centerY.equalTo(dataOfCompletionTextfield.textField)
            make.height.width.equalTo(24)
        }
        
        let dateDescriptionLabel = ContentLabel(hexStr: "#ED3E3EFF")
        dateDescriptionLabel.text = NSLocalizedString("pvd.detail.editaddress.dataofcompletion.descrip", comment: "")
        dateDescriptionLabel.numberOfLines = 0
        contentView.addSubview(dateDescriptionLabel)
        dateDescriptionLabel.snp.makeConstraints { (make) in
            make.top.equalTo(dataOfCompletionTextfield.snp.bottom).offset(30)
            make.left.right.equalTo(descripLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        //显示image的图片列表
        contentView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(dateDescriptionLabel.snp.bottom).offset(12)
            make.left.right.equalTo(descripLabel)
            self.tableViewHeightConstraint = make.height.greaterThanOrEqualTo(0).constraint
            make.bottom.equalToSuperview()
        }
        tableView.isScrollEnabled = false
        tableView.separatorStyle = .none
        tableView.register(PanelInstalledESCImageCell.self, forCellReuseIdentifier: PanelInstalledESCImageCell.reuseCellIdentifier)
        //绑定数据
        dataObserver.bind(to: tableView.rx.items(cellIdentifier: PanelInstalledESCImageCell.reuseCellIdentifier,cellType: PanelInstalledESCImageCell.self)){(row, imageModel, cell) in
            cell.setData(imageModel.image,index: row)
        }.disposed(by: self.disposeBag)
        //选择某一样
        tableView.rx.itemSelected.bind{ [weak self](indexPath) in
            self?.escImageViewTapBtnClosure?(indexPath.row)
        }
        .disposed(by: disposeBag)
        //观察tableview的高度
        tableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.tableViewHeightConstraint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
        
        //bottom view
        pickerBackView.backgroundColor = UIColor.black.withAlphaComponent(0.8)
        pickerBackView.isHidden = true
        self.addSubview(pickerBackView)
        pickerBackView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        //
        datePicker.backgroundColor = .white
        pickerBackView.addSubview(datePicker)
        datePicker.backgroundColor = .white
        datePicker.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(216)
        }
        
        let btnBackView = UIView()
        btnBackView.backgroundColor = .white
        btnBackView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        pickerBackView.addSubview(btnBackView)
        btnBackView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(64)
            make.bottom.equalTo(datePicker.snp.top)
        }
        
        let cancelBtn = BaseButton()
        cancelBtn.setTitle("Cancel", for: UIControl.State.normal)
        cancelBtn.setTitleColor(UIColor(hexStr: "#379657"), for: UIControl.State.normal)
        cancelBtn.setFont(R.font.interMedium(size: 17))
        btnBackView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.bottom.equalToSuperview()
            make.width.equalTo(100)
        }
        
        
        let doneBtn = BaseButton()
        doneBtn.setTitle("Done", for: UIControl.State.normal)
        doneBtn.setTitleColor(UIColor(hexStr: "#379657"), for: UIControl.State.normal)
        doneBtn.setFont(R.font.interMedium(size: 17))
        btnBackView.addSubview(doneBtn)
        doneBtn.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview()
            make.right.equalToSuperview().offset(-10)
            make.width.equalTo(100)
        }
        
        calenderBtn.tag = 0
        calenderBtn.addTarget(self, action: #selector(showDatePicker(_:)), for: UIControl.Event.touchUpInside)
        doneBtn.addTarget(self, action: #selector(donePicker), for: UIControl.Event.touchUpInside)
        cancelBtn.addTarget(self, action: #selector(cancelPicker), for: UIControl.Event.touchUpInside)
        
        datePicker.delegate = self
        datePicker.dataSource = self
        
    }
    //根据月份获取结果
    private func getMonthDescripByMonth(_ month: Int)->(String,String){
        var ret: String = ""
        var ret2: String = ""
        switch month {
        case 1:
            ret = "January"
            ret2 = "01"
        case 2:
            ret = "February"
            ret2 = "02"
        case 3:
            ret = "March"
            ret2 = "03"
        case 4:
            ret = "April"
            ret2 = "04"
        case 5:
            ret = "May"
            ret2 = "05"
        case 6:
            ret = "June"
            ret2 = "06"
        case 7:
            ret = "July"
            ret2 = "07"
        case 8:
            ret = "August"
            ret2 = "08"
        case 9:
            ret = "September"
            ret2 = "09"
        case 10:
            ret = "October"
            ret2 = "10"
        case 11:
            ret = "November"
            ret2 = "11"
        case 12:
            ret = "December"
            ret2 = "12"
        default:
            break
        }
        return (ret,ret2)
    }
    func initData(){
        let calendar: Calendar = Calendar.current
        self.currentYear = calendar.component(.year, from: Date())
        self.currentMonth = calendar.component(.month, from: Date())
        self.currentDay = calendar.component(.day, from: Date())
        yearsForPicker = ["\(currentYear - 1)", "\(currentYear + 0)"]
        //去年今天的下一天
        let lastMinMonth = calendar.component(.month, from: Date())
        for month in lastMinMonth ... 12 {
            let (ret,ret2)  = self.getMonthDescripByMonth(month)
            monthsForLastYear.append(ret)
            monthsNumberForLastYear.append(ret2)
        }
        //今年的月份
        for month in 1 ... currentMonth{
            let (ret,ret2)  = self.getMonthDescripByMonth(month)
            monthsForThisYear.append(ret)
            monthsNumberForThisYear.append(ret2)
        }
        //去年的月份
        self.setDefaultData()
    }
    func setDefaultData(){
        self.selectYear = yearsForPicker[1]
        self.selectMonth = monthsNumberForThisYear[self.currentMonth - 1]
        if currentDay < 10 {
            self.selectDay = "0\(currentDay)"
        }else{
            self.selectDay = "\(currentDay)"
        }
    }
    @objc func cancelPicker(){
        self.calenderBtn.tag = 0
        self.pickerBackView.isHidden = true
    }
    @objc func donePicker(){
        self.calenderBtn.tag = 0
        self.pickerBackView.isHidden = true
        
        let dateStr: String = self.selectDay + "-" + self.selectMonth + "-" + self.selectYear
        self.dataOfCompletionTextfield.textField.text = dateStr
        self.dataOfCompletionTextfield.textField.sendActions(for: .editingChanged)
    }
    
    @objc
    func showDatePicker(_ sender: UIButton){
        
        self.setDefaultData()
        self.datePicker.selectRow(1, inComponent: 2, animated: true)
        self.datePicker.reloadComponent(1)
        self.datePicker.selectRow(self.currentMonth - 1, inComponent: 1, animated: true)
        self.datePicker.reloadComponent(0)
        self.datePicker.selectRow(self.currentDay - 1, inComponent: 0, animated: true)
        
        if sender.tag == 0{
            sender.tag = 1
            pickerBackView.isHidden = false
        }else{
            sender.tag = 0
            pickerBackView.isHidden = true
        }
    }
    func setData(_ model: PVDDetailModel,date: String,list: [BrowseImageData]){
        installedPanelsCnt.text = "\(model.pvd_serial_numbers.count)"
        installationAddressLabel.text = model.install_address.installation_address
        dataOfCompletionTextfield.textField.text = date
        
        self.dataObserver.accept(list)
        
    }
}
extension PanelInstallAlertView: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    //MARK: - 获取当前月份字符串
    private func getCurrentMonthStr()->String{
        var currentMonthStr: String = ""
        if self.currentMonth < 10 {
            currentMonthStr = "0\(self.currentMonth)"
        }else{
            currentMonthStr = "\(self.currentMonth)"
        }
        return currentMonthStr
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {//day
            var days: Int!
            if selectYear == "\(self.currentYear)" {//今年
                if selectMonth == self.getCurrentMonthStr() {//当月
                    days = self.currentDay
                }else{
                    days = DateUtil().howManyDaysOfMonth(inThisYear: self.currentYear, withMonth: Int(selectMonth)!)
                }
            }else{//去年
                days = DateUtil().howManyDaysOfMonth(inThisYear: self.currentYear - 1, withMonth: Int(selectMonth)!)
                //去年当月的日期从today的下一天开始
                if self.selectMonth == self.getCurrentMonthStr() {
                    days = days - self.currentDay
                }
            }
            return days
        }else if component == 1{//month
            //this year
            if selectYear == "\(self.currentYear)" {
                return self.monthsForThisYear.count
            }else {//last year
                return self.monthsForLastYear.count
            }
        }else {//year
            return 2
            
        }
    }
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return APPConfig.WidthForPortrait / 3
    }
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 40
    }
    //MARK: - 设置选项框各选项的内容,继承于UIPickViewDelegate协议
//    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
//        if component == 0 {//day
//            var days: Int = 0
//            if self.selectYear == "\(currentYear - 1)" && self.selectMonth == self.getCurrentMonthStr(){//去年当前月的日期从去年today下一天开始
//                days = self.currentDay + (row + 1)
//            }else{//其他
//                days = row + 1
//            }
//            if days < 10 {
//                return "0\(days)"
//            }else{
//                return "\(days)"
//            }
//        }else if component == 1 {
//            if selectYear == "\(self.currentYear)" {//last year
//                return self.monthsForThisYear[row]
//            }else{
//
//                return self.monthsForLastYear[row]
//            }
//        }else {
//            return self.yearsForPicker[row]
//        }
//    }
    //MARK: - 根据row获取当前的days的显示值
    private func getDisplayDaysByRow(_ row: Int)->String{
        var days: Int = 0
        var ret: String = ""
        if self.selectYear == "\(currentYear - 1)" && self.selectMonth == self.getCurrentMonthStr(){//去年当前月的日期从去年today下一天开始
            days = self.currentDay + (row + 1)
        }else{//其他
            days = row + 1
        }
        if days < 10 {
            ret =  "0\(days)"
        }else{
            ret =  "\(days)"
        }
        return ret
    }
    //修改每行的字体大小和颜色(这个(viewForRow)函数与上面的(titleForRow)函数一般时选择其中一个,如果不对每行选项进行样式设置的话就选择(titleForRow)函数)
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        //设置分割线的颜色
        for subView in pickerView.subviews {
            if subView.frame.size.height <= 1 {
                subView.isHidden = false
                subView.backgroundColor = UIColor(red: 236 / 255, green: 237 / 255, blue: 240 / 255, alpha: 1.0)
            }
        }
        let titleLabel = ContentLabel(R.font.interMedium(size: 17))
        titleLabel.textAlignment = NSTextAlignment.center
        
        if component == 0 {//day
            titleLabel.text = self.getDisplayDaysByRow(row)
        }else if component == 1 {
            if selectYear == "\(self.currentYear)" {//this year
                titleLabel.text =  self.monthsForThisYear[row]
            }else{
                titleLabel.text =  self.monthsForLastYear[row]
            }
        }else {
            titleLabel.text = self.yearsForPicker[row]

        }
        return titleLabel
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {//day
            self.selectDay = self.getDisplayDaysByRow(row)
        }else if component == 1 {
            if selectYear == "\(self.currentYear)"{//this year
                self.selectMonth = self.monthsNumberForThisYear[row]
            }else{//this year
                self.selectMonth = self.monthsNumberForLastYear[row]
            }
            
            pickerView.reloadComponent(0)
        }else{
            var currentMonthStr: String = ""
            if self.currentMonth < 10 {
                currentMonthStr = "0\(self.currentMonth)"
            }else{
                currentMonthStr = "\(self.currentMonth)"
            }
            
            self.selectYear = self.yearsForPicker[row]
            pickerView.reloadComponent(1)
            //month
            if selectYear == "\(self.currentYear)" {//切换回今年后，当前选中的月份未必在在今年的月份中存在，如果不存在默认为当前月
                if !self.monthsNumberForThisYear.contains(selectMonth) {//包含选中的月份
                    if self.currentMonth < 10 {
                        self.selectMonth = "0\(self.currentMonth)"
                    }else{
                        self.selectMonth = "\(self.currentMonth)"
                    }
                    //
                    if self.currentDay < 10 {
                        self.selectDay = "0\(self.currentDay)"
                    }else{
                        self.selectDay = "\(self.currentDay)"
                    }
                }else{
                    if  selectMonth == currentMonthStr {
                        if self.currentDay < 10 {
                            self.selectDay = "0\(self.currentDay)"
                        }else{
                            self.selectDay = "\(self.currentDay)"
                        }
                    }
                }
            }
            if  selectMonth == currentMonthStr {//切换到当前月时（去年或今年），要刷新日数据
                pickerView.reloadComponent(0)
            }
        }
    }
}

